package master.userInterface;

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;


import master.QuantumNetwork;
import master.event.*;

import gates.QuantumGate;

public class GateMenuPanel extends JPanel implements GateGenerationListener,GateGenerationEventInitiator,ActionListener{
	
	public void gateGenerated(GateGenerationEvent e) {
		generateGate(e.getGate(),e.getConstructorArguments());
	}
	QuantumNetwork k;
	JButton addGateBut = new JButton("Add Gate");
	JButton removeGateBut = new JButton("Remove Gate");
	GateComboBox gateAdder;
	NetworkComboBox gateSelector;
	public GateMenuPanel(GateComboBox b, QuantumNetwork k){
		addGateBut.addActionListener(this);
		removeGateBut.addActionListener(this);
		addGateGenerationListener(k);
		gateSelector = new NetworkComboBox(k);
		this.k = k;
		this.gateAdder = b;
		for(GateIOPanel pan :b.getPopupPanels())
			pan.addGateGenerationListener(this);
		
		setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		
		c.anchor = c.NORTH;
		
		c.gridx = 0;
		c.gridy = 0;
		add(gateAdder, c);
		c.gridx = 1;
		add(addGateBut,c);
		
		c.gridx = 0;
		c.gridy = 1;
		add(gateSelector,c);
		c.gridx = 1;
		add(removeGateBut,c);
	}
	
	
	List<GateGenerationListener> listeners = new ArrayList<GateGenerationListener>();
	public void addGateGenerationListener(GateGenerationListener gglListener){
		if(gglListener!=null)listeners.add(gglListener);
	}
	
	public void generateGate(QuantumGate gate,Object [] constructorArguments){
		for(GateGenerationListener gglListener : listeners)
			gglListener.gateGenerated(new GateGenerationEvent(gate,constructorArguments));
	}
	
	
	public void actionPerformed(ActionEvent e) {
		if(e.getSource().equals(addGateBut)){
			JFrame popup = new JFrame();
			GateIOPanel [] p;
			p = gateAdder.getPopupPanels();
			popup.getContentPane().add(
					p[ gateAdder.getSelectedIndex() ]
					);
			popup.setVisible(true);
			popup.setSize(400,200);
			popup.setAlwaysOnTop(true);
			popup.setTitle(gateAdder.getSelectedItem().toString());
		}else if(e.getSource().equals(removeGateBut)){
				k.removeGate( gateSelector.getSelectedIndex() );
		}
	}
	
}
